package com.cesce.batch.cobros.service;

import java.io.File;
import java.io.InputStream;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;

import com.cesce.batch.cobros.exceptions.FTPException;

//@Service
public class FtpImpl implements FtpService {

	public String getServer() {
		return server;
	}

	public void setServer(String server) {
		this.server = server;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getDirectory() {
		return directory;
	}

	public void setDirectory(String directory) {
		this.directory = directory;
	}

	private String server;
	private String username;
	private String password;
	private String directory;

  
	
	public InputStream getFileByName(String name) throws FTPException {
	
	    FTPFile ftpFile=null;
	    
	    try {
	        FTPClient f=new FTPClient();
	        f.connect(server);
	        f.login(username, password);
	        FTPFile[] files = f.listFiles(directory);
	        for (int i = 0; i < files.length; i++) {
	            ftpFile = files[i];
	            if(ftpFile.getName().equalsIgnoreCase(name)) break;         
	        }

	        return f.retrieveFileStream(directory+ftpFile.getName());
	        
	    } catch (Throwable e) {
	        throw new FTPException("No es posible acceder al fichero " + name,e);
	    }
	}
	
	@Override
	public void setFileWithName(InputStream is, String name) throws FTPException {
			    
	    try {
	        FTPClient f=new FTPClient();
	        f.connect(server);
	        f.login(username, password);
            f.changeWorkingDirectory(directory);
			

			f.setFileType(org.apache.commons.net.ftp.FTPClient.ASCII_FILE_TYPE); //Con este tipo genera bien el fichero
			

			boolean storeOk = f.storeFile(name, is);						
			
			f.logout();
			f.disconnect();
			
			if(!storeOk) throw new FTPException("No es posible transferir el fichero " + name);
	        
	    } catch (Throwable e) {
	        throw new FTPException("No es posible transferir el fichero " + name,e);
	    }
	}

}
